<template>
  <div class="orderBook">
    <div class="head">
      <!--div class="orderBookTypes">
        <span class="item all"><img src="./../images/orderbook-all.png" @click="changeFullType(-1)" :class="{active: fullType === -1}"></span>
        <span class="item buy"><img src="./../images/orderbook-buy.png" @click="changeFullType(1)" :class="{active: fullType === 1}"></span>
        <span class="item sell"><img src="./../images/orderbook-sell.png" @click="changeFullType(0)" :class="{active: fullType === 0}"></span>
      </div-->
      <div class="orderBookDeep">
        {{lang['depth']}}
        <select v-model="orderBookPrecision" @change="changePrecision">
          <option :value="item.value" v-for="item in deepList">{{item.value > 0 ? (lang['two decimals'].replace('{decimal}', item.text)) : lang['integer']}}</option>
        </select>
        <!--{{lang['deep merging']}}-->
      </div>
    </div>
    <div class="order">
      <div class="orderSell">
        <div class="orderBookListHead">
          <div class="th" :style="orderBookGridStyle.price">{{lang['price']}} ({{pair.BuyerCoinCode}})</div>
          <div class="th" :style="orderBookGridStyle.quantity">{{lang['quantity']}} ({{pair.SellerCoinCode}})</div>
          <div class="th" :style="orderBookGridStyle.total">{{lang['accumulative total']}} ({{pair.SellerCoinCode}})&nbsp;</div>
        </div>
        <div class="orderBookListWrap" :style="{height: orderBookListWrapHeight + 'px'}">
          <div class="orderBookList sellList" :style="{height: sellListRealHeight + 'px', 'margin-top': sellListTop + 'px'}">
            <div class="tr"
              v-for="index in orderBookDeep"
              :class="{hasMyQuantity: mySellQuantity[index - 1] && mySellQuantity[index - 1].side === 1}">
              <div class="td" :style="orderBookGridStyle.price" :ref="'sellListRow' + index" @click="fillInPrice($event, 1)">{{'&nbsp;'}}</div>
              <div class="td" :style="orderBookGridStyle.quantity" :ref="'sellListRow' + index" @click="fillInQuantity($event, 1, 'sellListRow' + index)"></div>
              <div class="td" :style="orderBookGridStyle.total" :ref="'sellListRow' + index" @click="fillInQuantity($event, 1,'sellListRow' + index)"></div>
              <p class="orderedQuantity"
                v-show="mySellQuantity[index - 1] && mySellQuantity[index - 1].side === 1"
                v-text="mySellQuantity[index - 1] && mySellQuantity[index - 1].quantity"
              ></p>
              <p class="totalWidth" ref="sellTotalWidths"></p>
            </div>
          </div>
        </div>
      </div>
      <div class="orderBookTip">
        <p class="latest">{{lang['new price']}}:
          <em v-show="latestPrice.price > 0" :class="{up: latestPrice.trend === 1, down: latestPrice.trend === 0}" @click="fillInPrice($event, 2)">
            {{latestPrice.price | currency('USD', '', pair.buyerPrecision) | fillDecimal(pair.buyerPrecision)}}
          </em>
          <img v-show="latestPrice.trend === 1" src="../../../assets/images/head/arrow-up-green.png">
          <img v-show="latestPrice.trend === 0" src="../../../assets/images/head/arrow-down-red.png">
        </p>
        <p class="change">
          {{lang['24h Change']}}:
          <em :class="{up: pair.roseVal > 0, down: pair.roseVal < 0, noChange: pair.roseVal === 0}">
            {{pair.roseStr}}
          </em>
        </p>
      </div>
      <div class="orderBuy">
        <div class="orderBookListHead">
          <div class="th" :style="orderBookGridStyle.price">{{lang['price']}} ({{pair.BuyerCoinCode}})</div>
          <div class="th" :style="orderBookGridStyle.quantity">{{lang['quantity']}} ({{pair.SellerCoinCode}})</div>
          <div class="th" :style="orderBookGridStyle.total">{{lang['accumulative total']}} ({{pair.SellerCoinCode}})&nbsp;</div>
        </div>
        <div class="orderBookListWrap" :style="{height: orderBookListWrapHeight + 'px'}">
          <div class="orderBookList buyList" :style="{height: buyListRealHeight + 'px'}">
            <div class="tr"
              v-for="index in orderBookDeep"
              :class="{hasMyQuantity: myBuyQuantity[index - 1] && myBuyQuantity[index - 1].side === 0}">
              <div class="td" :style="orderBookGridStyle.price" :ref="'buyListRow' + index" @click="fillInPrice($event, 0)">{{'&nbsp;'}}</div>
              <div class="td" :style="orderBookGridStyle.quantity" :ref="'buyListRow' + index" @click="fillInQuantity($event, 0, 'buyListRow' + index)"></div>
              <div class="td" :style="orderBookGridStyle.total" :ref="'buyListRow' + index" @click="fillInQuantity($event, 0, 'buyListRow' + index)"></div>
              <p class="orderedQuantity"
                v-show="myBuyQuantity[index - 1] && myBuyQuantity[index - 1].side === 0"
                v-text="myBuyQuantity[index - 1] && myBuyQuantity[index - 1].quantity"
              ></p>
              <p class="totalWidth" ref="buyTotalWidths"></p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// import name from '@/components/...'
import $ from 'jquery'
import Utils from '@/utils/Utils.js'
import EventBus from '@/service/EventBus.js'
import realtimePush from './../js/realtimePush.js'
import Decimal from '@/libs/decimal.min.js'
import commonFilter from '@/filters/common.js'

export default {
  name: 'OrderBook',
  props: [
    'lang',
    'winMinHeight'
  ],
  data () {
    return {
      pair: {},
      sellList: [],
      buyList: [],
      orderBookPrecision: 2,
      defaultOrderBookPrecision: 2,
      selectedOrderBookPrecision: 2,
      firstChangePrecision: true,
      // 枚举的深度
      enumDeep: [
        {
          text: 0, // '整数'
          value: 0
        }, {
          text: '1', // 1位小数
          value: 1
        }, {
          text: '2', // 位小数
          value: 2
        },
        {
          text: '3',
          value: 3
        },
        {
          text: '4',
          value: 4
        },
        {
          text: '5',
          value: 5
        },
        {
          text: '6',
          value: 6
        },
        {
          text: '7',
          value: 7
        },
        {
          text: '8',
          value: 8
        },
        {
          text: '10',
          value: 10
        }

      ],
      deepList: [],
      // spread: 0,
      // fullType: -1, // 0sell 1buy
      orderBookGridStyle: {
        price: {width: '33%', 'text-indent': '4px'},
        quantity: {width: '34%', 'text-align': 'right'},
        total: {width: '33%', 'text-align': 'right'}
      },
      orderBookDeep: 50,
      orderBookListWrapHeight: 0,
      // sellFullHeight: 0,
      orderBookHeight: 0,
      // orderBookFullHeight: 0,
      sellListTop: 0,
      sellListRealHeight: 0,
      buyListRealHeight: 0,
      tdHeight: 16,
      orderedQuantity: 0,
      orderSide: -1, // 1卖 0买
      inited: false,
      myOrderBook: {sellList: [], buyList: []}, // 显示我的委托列表
      mySellQuantity: [],
      myBuyQuantity: [],
      isResetSellListScroll: true,
      isResetBuyListScroll: true,
      latestPrice: {
        Price: '--'
      },
      sellListScrollTimer: null,
      pushOrderBookResult: {},
      $sellListWrap: null,
      $buyListWrap: null,
      isMouseOverSellList: false
    }
  },
  filters: {
    ...commonFilter
  },
  computed: {
    // 已经废弃，最好的卖价减最好的买价
    // spread () {
    //   if (!this.sellList.length || !this.buyList.length || !this.sellList || !this.buyList) return 0
    //   let sPrice = parseFloat(this.sellList[this.sellList.length - 1].Price) || 0 // 值可能是非数字，经过parseFloat转换为NaN，所以加||0
    //   let bPrice = parseFloat(this.buyList[0].Price) || 0
    //   if (!sPrice || !bPrice) return 0
    //   let spread = (new Decimal(sPrice)).sub(bPrice)
    //   spread = this.pair.TradingType === 0
    //     ? commonFilter.fillDecimal(spread.toFixed(), 2)
    //     : commonFilter.fillDecimal(spread.toFixed(), 6)
    //   return spread
    // }
  },
  methods: {
    fillInPrice (event, side) {
      // 点击卖的挂单，填入买入框，点击买的挂单，填入卖出框
      // let price = parseFloat(event.target.innerHTML)

      // 防-1e8
      let value = event.target.innerHTML.replace(/,/g, '').trim()
      let pre = new Decimal(value)
      let price = pre.toFixed()
      price && EventBus.$emit('fillInPrice', {price, side})
    },

    fillInQuantity (event, side, id) {
      if (id) {
        // 点击当前单需要同时发送价钱
        let value = this.$refs[id][0].innerHTML.replace(/,/g, '').trim()
        let pre = new Decimal(value)
        let price = pre.toFixed()
        price && EventBus.$emit('fillInPrice', {price, side})
      }

      // 填充数量
      let quantity = parseFloat(event.target.innerHTML.replace(/,/g, '').trim())
      quantity && EventBus.$emit('fillInQuantity', {quantity, side})
    },
    setDeepList () {
      // 0是币-钱交易，2是币-币交易
      // if (this.pair.TradingType === 0) {
      //   this.precisionList = this.CMPrecisionList
      // } else if (this.pair.TradingType === 2) {
      //   this.precisionList = this.CCPrecisionList
      //   this.pair.BuyerCoinCode === 'VHKD' && (this.precisionList = this.CMPrecisionList) // vhkd是2位
      // }
      let startIndex = 0
      let endIndex = 6
      switch (true) {
        case this.pair.buyerPrecision >= 8:
          startIndex = 3
          // endIndex = 9
          break
        case this.pair.buyerPrecision >= 6:
          startIndex = 3
          // endIndex = 7
          break
        case this.pair.buyerPrecision >= 2:
          startIndex = 0
          // endIndex = 3
          break
      }
      endIndex = this.pair.buyerPrecision + 1

      this.deepList = this.enumDeep.slice(startIndex, endIndex)
      this.defaultOrderBookPrecision = this.pair.buyerPrecision
      this.orderBookPrecision = this.pair.buyerPrecision
    },
    changePrecision () {
      this.firstChangePrecision = false
      this.init()
      realtimePush.switchPrecision(this.pair.TradingConfigID, this.orderBookPrecision >> 0) // 传整型
    },
    // 填充委托列表，防止抖动
    fillInOrderBook: (arr, type, orderBookDeep) => {
      if (!Array.isArray(arr)) return
      let gap = orderBookDeep - arr.length

      if (gap < 0) {
        // 若多了，则删除多余
        gap = Math.abs(gap)
        if (type === 0) {
          for (let i = 0; i < gap; i++) {
            arr.shift()
          }
          arr = arr.slice(gap)
        } else {
          for (let i = 0; i < gap; i++) {
            arr.pop()
          }
        }
      } else if (gap > 0) {
        // 若不够则填充
        for (let i = 0; i < gap; i++) {
          if (type === 0) {
            arr.unshift({
              Price: '&nbsp;',
              Amount: ' ',
              total: ' '
            })
          } else {
            arr.push({
              Price: '&nbsp;',
              Amount: ' ',
              total: ' '
            })
          }
        }
      }
    },
    renderBuyAndSellList: (list, type, vm) => { // 此方法经过在watch里调用，此方法里面调用的this无效，需要在watch传过来this)
      if (type === 0) {
        let item = {}
        for (let bl = vm.orderBookDeep - 1; bl >= 0; bl--) {
          item = list[bl] || {}
          vm.$refs[`sellListRow${bl + 1}`][0].innerHTML = commonFilter.formatThousands(item.Price) // + '&nbsp;'
          vm.$refs[`sellListRow${bl + 1}`][1].innerHTML = commonFilter.formatThousands(item.Amount) // item.Amount // + '&nbsp;'
          vm.$refs[`sellListRow${bl + 1}`][2].innerHTML = commonFilter.formatThousands(item.total) + '&nbsp;' // item.total + '&nbsp;'

          vm.$refs['sellTotalWidths'][bl].style.width = item.totalWidth
        }
      } else {
        for (let j = 0; j < list.length; j++) {
          vm.$refs[`buyListRow${j + 1}`][0].innerHTML = commonFilter.formatThousands(list[j].Price) // + '&nbsp;'
          vm.$refs[`buyListRow${j + 1}`][1].innerHTML = commonFilter.formatThousands(list[j].Amount) // list[j].Amount // + '&nbsp;'
          vm.$refs[`buyListRow${j + 1}`][2].innerHTML = commonFilter.formatThousands(list[j].total) + '&nbsp;' // list[j].total

          vm.$refs['buyTotalWidths'][j].style.width = list[j].totalWidth
        }
      }
    },
    // 原来没有total字段，需要自己计算
    createTotal: (arr, type) => { // type:0是卖，1是买
      if (!arr || !arr.length) return []
      if (type === 0) arr.reverse()
      let total
      for (var i = 0; i < arr.length; i++) {
        total = new Decimal(arr[i].Amount)
        arr[i].total = total.add((arr[i - 1] && arr[i - 1].total) || 0).toFixed() // 加前一条的total
      }
      if (type === 0) arr.reverse()
    },
    // 创建total横条宽度
    createTotalWidth (arr, type) {
      if (!arr || !arr.length) return []
      if (type === 1) arr.reverse()
      let maxTotal
      for (var i = 0; i < arr.length; i++) {
        if (!maxTotal && (arr[i].total >> 0)) {
          arr[i].totalWidth = '100%'
          maxTotal = arr[i].total
        }
        arr[i].totalWidth = (arr[i].total / maxTotal * 100 || 0) + '%'
      }
      if (type === 1) arr.reverse()
    },
    // 合并深度（即小数位）
    mergeDeepWithArray (list, key, precision) {
      let mergedRecord = {}
      let mergedRecordIndex = 0
      let mergedList = []
      let dotPos = -1
      let priceStr = ''
      let temp
      precision = precision >> 0
      for (let i = 0; i < list.length; i++) {
        priceStr = list[i][key].toString()
        dotPos = priceStr.indexOf('.')

        if (dotPos > -1) {
          priceStr = priceStr.slice(0, dotPos + precision + 1)
        }

        if (!mergedRecord[priceStr]) {
          mergedRecord[priceStr] = {
            index: mergedRecordIndex
          }
          mergedList[mergedRecordIndex] = {
            price: priceStr,
            quantity: list[i].Num,
            side: list[i].TradeSide
          }
          mergedRecordIndex++
        } else {
          temp = new Decimal(mergedList[mergedRecord[priceStr].index].quantity)
          mergedList[mergedRecord[priceStr].index].quantity = temp.add(list[i].Num).toFixed()
        }
      }

      return mergedList
    },
    // 在委托列表里显示自己的
    showMyQuantity () {
      let mergedMySellList = this.mergeDeepWithArray(this.myOrderBook.sellList, 'Price', this.orderBookPrecision)
      let mergedMyBuyList = this.mergeDeepWithArray(this.myOrderBook.buyList, 'Price', this.orderBookPrecision)
      this.fillDecimalWithArray(mergedMySellList, 'quantity', this.pair.sellerPrecision)
      this.fillDecimalWithArray(mergedMyBuyList, 'quantity', this.pair.sellerPrecision)

      this.mySellQuantity = []
      // 遍历卖
      for (let i = 0; i < this.sellList.length; i++) {
        for (let j = 0; j < mergedMySellList.length; j++) {
          if (parseFloat(this.sellList[i].Price) === parseFloat(mergedMySellList[j].price) && mergedMySellList[j].side === 1) {
            this.mySellQuantity[i] = mergedMySellList[j]
            this.mySellQuantity[i].quantity = commonFilter.formatThousands(mergedMySellList[j].quantity)
          }
        }
      }

      this.myBuyQuantity = []
      // 遍历买
      for (let i = 0; i < this.buyList.length; i++) {
        for (let j = 0; j < mergedMyBuyList.length; j++) {
          if (parseFloat(this.buyList[i].Price) === parseFloat(mergedMyBuyList[j].price) && mergedMyBuyList[j].side === 0) {
            this.myBuyQuantity[i] = mergedMyBuyList[j]
            this.myBuyQuantity[i].quantity = commonFilter.formatThousands(mergedMyBuyList[j].quantity)
          }
        }
      }
    },
    // 过滤掉无效数量的项
    filterNoQuantityItem (list) {
      return list.filter((item) => {
        return parseFloat(item.Amount) > 0
      })
    },
    setList (_list, side) {
      let list = _list.slice(0)
      this.createTotal(list, side)
      this.fillInOrderBook(list, side, this.orderBookDeep)
      this.createTotalWidth(list, side)
      // let p = this.defaultOrderBookPrecision !== (this.orderBookPrecision >> 0) ? this.orderBookPrecision : this.pair.buyerPrecision
      Utils.fixOriginalPrecisionWithArray(list, 'Price')
      Utils.fixOriginalPrecisionWithArray(list, 'Amount')
      Utils.fixOriginalPrecisionWithArray(list, 'total')
      this.fillDecimalWithArray(list, 'Price', this.pair.buyerPrecision)
      this.fillDecimalWithArray(list, 'Amount', this.pair.sellerPrecision)
      this.fillDecimalWithArray(list, 'total', this.pair.sellerPrecision)
      list = this.filterNoQuantityItem(list)

      side === 0 ? (this.sellList = list) : (this.buyList = list)
      side === 0 ? this.calcSellListRealHeight() : this.calcBuyListRealHeight()
      this.renderBuyAndSellList(list, side, this)

      // 刷新自己的委托显示
      this.showMyQuantity()
    },
    // changeFullType (type) {
    //   this.fullType = type
    //   if (type === 0) {
    //     this.cleanSellEmpty()
    //   } else {
    //     this.fillInOrderBook(this.sellList, 0, this.orderBookDeep)
    //     this.createTotalWidth(this.sellList, 0)
    //     this.renderBuyAndSellList(this.sellList, 0, this)
    //   }
    // },
    fillDecimalWithArray (list = [], key, prec) {
      list.forEach((item) => {
        if (parseFloat(item[key])) {
          item[key] = commonFilter.fillDecimal(item[key], prec)
        }
      })
    },
    // 删除空格
    // cleanSellEmpty () {
    //   this.sellFullHeight = this.orderBookFullHeight
    //   this.sellList.forEach((v, i) => {
    //     if (!parseFloat(v.Price) && !parseFloat(v.quantity) && !parseFloat(v.total)) {
    //       this.$refs[`sellListRow${i + 1}Col1`][0].innerHTML = ''
    //       this.$refs[`sellListRow${i + 1}Col2`][0].innerHTML = ''
    //       this.$refs[`sellListRow${i + 1}Col3`][0].innerHTML = ''

    //       this.sellFullHeight -= this.tdHeight
    //     }
    //   })
    // },
    calcHeight () {
      let winHeight = $(window).height()
      // if (winHeight < this.winMinHeight) {
      //   winHeight = this.winMinHeight
      // }
      let headHeight = $('.pageHead').outerHeight()
      let orderBookHead = $('.orderBook>.head').outerHeight()
      let sellHeadHeight = $('.col2 .orderBookListHead').eq(0).outerHeight()
      let orderBookTipHeight = $('.orderBookTip').outerHeight()
      let tradeBoxHeight = $('.tradeWrap').outerHeight()

      // 买卖盘高度总和
      this.orderBookHeight = winHeight - headHeight - orderBookHead - sellHeadHeight - orderBookTipHeight - tradeBoxHeight
      // 买卖各有几条
      // this.orderBookDeep = 50 // Math.floor(this.orderBookHeight / this.tdHeight)

      // 买卖盘各单个容器高度（精确）
      this.orderBookListWrapHeight = this.orderBookHeight / 2 // this.orderBookDeep * this.tdHeight / 2
      // 满屏高度
      // this.orderBookFullHeight = this.orderBookListWrapHeight * 2

      // tradingView和orderBook同高
      this.$nextTick(() => {
        EventBus.$emit('readyOrderBookHeight')
      })
    },
    // 计算list真实高度，动态控制滚动条
    calcSellListRealHeight () {
      let oldSellListRealHeight = this.sellListRealHeight
      let realLen = 0
      // let topLen = 0
      let item = {}
      for (let i = this.orderBookDeep - 1; i >= 0; i--) {
        item = this.sellList[i] || {}
        if (parseFloat(item.Price)) {
          ++realLen
        } else {
          // ++topLen
        }
      }
      this.sellListRealHeight = realLen * this.tdHeight
      // $('.orderBookListWrap:eq(0) .tr:eq(0)').css('margin-top', -(topLen * this.tdHeight) + 'px')

      // 若list矮于wrap，则添加margin
      let gap = Math.max(this.orderBookListWrapHeight - this.sellListRealHeight, 0)
      this.sellListTop = gap

      this.$nextTick(() => {
        let niceScroll = this.sellListNiceScroll

        niceScroll.resize()

        let lastScrollGap = this.sellListRealHeight - oldSellListRealHeight
        // 滚动条修复，setScrollTop doScrollTop
        if (this.isMouseOverSellList) {
          niceScroll.setScrollTop(niceScroll.newscrolly + lastScrollGap, 0)
        }

        // 如果鼠标是移到外面，则向下滚动到底
        if (!this.isMouseOverSellList) {
          niceScroll.setScrollTop(10000, 0)
        }

        this.isResetSellListScroll && niceScroll.doScrollTop(10000, 0)
        this.isResetSellListScroll = false
      })
    },
    calcBuyListRealHeight () {
      let realLen = 0
      for (let i = 0; i < this.buyList.length; i++) {
        if (parseFloat(this.buyList[i].Price)) {
          ++realLen
        } else {
          break
        }
      }
      this.buyListRealHeight = realLen * this.tdHeight
      this.$nextTick(() => {
        let niceScroll = this.buyListNiceScroll
        niceScroll.resize()

        this.isResetBuyListScroll && niceScroll.doScrollTop(0, 0)

        this.isResetBuyListScroll = false
      })
    },
    // 封装以便setTimeout调用
    sellListScroll () {
      let result = this.pushOrderBookResult
      this.setList(result.Asks, 0)
    },
    init () {
      // 每次切换需要
      this.isResetSellListScroll = true
      this.isResetBuyListScroll = true

      // 调整布局只需要初始化一次，之后要在窗口改变时再调整
      if (!this.inited) {
        this.calcHeight()

        // 动态适应
        $(window).resize(() => {
          this.calcHeight()
          this.$nextTick(() => {
            this.calcSellListRealHeight()
            this.calcBuyListRealHeight()
          })
        })
      }

      if (this.firstChangePrecision) {
        this.setDeepList()
      }

      this.$http.post('Trade/GetHandicap', {
        tradingConfigId: this.pair.TradingConfigID,
        deep: this.orderBookDeep,
        precision: this.orderBookPrecision
      }, {
        // mock: 'orderbook'
      }).then((res) => {
        this.setList(res.Data.SellHandicapList || [], 0)
        this.setList(res.Data.BuyHandicapList || [], 1)

        // this.fullType !== -1 && this.changeFullType(this.fullType)
        EventBus.$emit('updateOrderBookBestPrices', [this.sellList[this.sellList.length - 1], this.buyList[0]])
      })

      this.inited = true
    }
  },
  created () {
    EventBus.$on('switchPair', (pair) => {
      this.pair = pair
      this.firstChangePrecision = true
      this.init()
    })

    EventBus.$on('pushOrderBook', (result) => {
      // 供sellListScroll函数使用
      this.pushOrderBookResult = result

      clearTimeout(this.sellListScrollTimer)
      // 推送太快了会影响滚动条校正，故限制到20ms
      this.sellListScrollTimer = setTimeout(this.sellListScroll, 20)

      this.setList(result.Bids, 1)
    })

    EventBus.$on('sendMyOrderBook', (myOrderBook) => {
      this.myOrderBook = myOrderBook
      this.showMyQuantity()
    })

    EventBus.$on('updateCurrentPair', (pair) => {
      this.pair = pair
      // 处理最新价
      pair.Newest = (new Decimal(pair.Newest || 0)).toFixed()
      this.latestPrice = {
        price: pair.Newest,
        trend: pair.Rose > 0 ? 1 : 0
      }
    })

    /* EventBus.$on('updateLatestPrice', (info) => {
      info.price = (new Decimal(info.price || 0)).toFixed()
      this.latestPrice = info
      console.log(info)
    }) */

    // 订单下单买入、卖出成功后
    EventBus.$on('buyOrsallComplete', (state) => {
      this.init()
    })
  },
  mounted () {
    this.$sellListWrap = $('.orderBookListWrap:eq(0)')
    this.$buyListWrap = $('.orderBookListWrap:eq(1)')
    this.sellListNiceScroll = this.$sellListWrap.niceScroll({autohidemode: false, scrollspeed: 0})
    this.buyListNiceScroll = this.$buyListWrap.niceScroll({autohidemode: false, scrollspeed: 0})
    this.$sellListWrap
    // 若鼠标在卖盘内，则不自动滚到底
    .mouseleave(() => {
      this.isMouseOverSellList = false
    })
    // 若鼠标在卖盘外，则自动滚动底
    .mouseenter(() => {
      this.isMouseOverSellList = true
    })
  }
}
</script>

<style lang="less">
@import "./../../../mixins.less";
@white: #b5b8c0;
// @tradingModuleBgColor
// @tradingBorder

.tradingPage {

  .orderBook {
    float: left;
    overflow: hidden;
    width: @orderBookWidth;
    background-color: @tradingModuleBgColor;

    .head {
      .mix-clearfix;
      height: 28px;
      line-height: 28px;
      background-color: @tradingHeadBgColor;
    }
  }

  .orderBookTypes {
    float: left;

    .item {
      float: left;
      margin-top: 4px;
      margin-right: 8px;
      width: 26px;
      height: 18px;
      cursor: pointer;

      img {
        width: 100%;
        height: 100%;
        border: 1px solid #4c5463;

        &.active {
          border-color: #818a9a;
        }
      }
    }
  }

  .orderBookDeep {
    display: flex;
    align-items: center;
    margin-left: 6px;
    height: 28px;
    color:#ccc;
    select {
      margin-left: 6px;
      height: 20px;
      color: #ccc;
      border-color: #9a9c9e;
      background-color: transparent;

      option {
        background-color: #303641;
      }
    }
  }

  .orderBookListHead {
    width: 354px - @tradingScrollWidth;
    .mix-clearfix();

    .th {
      float: left;
      height: 30px;
      line-height: 30px;
      white-space: nowrap;
      font-size: 12px;
      font-weight: normal;
      color: #9a9c9e;
    }
  }

  .orderBookListWrap {
    outline: none; // 火狐虚线
  }

  .sell {
    .orderBookListHead {
      display: none;
    }
  }

  .flex {
    .order {
      display: flex;
      flex-direction: column;

      .orderBuy {
        .orderBookListHead {
          display: none;
        }
      }
    }
  }

  .orderBookList {
    overflow: hidden;
    width: 100%;
    font-size: 12px;
    color: @white;

    .tr {
      .mix-clearfix();
      position: relative;
      height: 16px;
      line-height: 16px;
      box-sizing: border-box;
    }

    .td {
      float: left;
      cursor: pointer;

      &:hover {
        font-weight: bold;
      }
    }

    .orderedQuantity {
      position: absolute;
      top: 0;
      left: 0;
      width: 43%;
      height: 100%;
      text-align: right;
      box-sizing: border-box;
      pointer-events: none;
    }
    .totalWidth {
      position: absolute;
      z-index: -1;
      top: 0;
      right: 0;
      width: 0;
      height: 100%;
    }
  }

  .sellList, .buyList {
    position: relative;
    z-index: 1;
  }

  .sellList {
    position: absolute;
    // bottom: 0;
    left: 0;

    .td:first-of-type {
      color: @downColor;
    }
    .totalWidth {
      background-color: #482833;
    }

    @darkDown: #C52628;
    .tr.hasMyQuantity {
      color: @darkDown;
      line-height: 14px;
      border: 1px dashed @darkDown;

      .td:first-of-type {
        color: @darkDown;
      }
    }
  }
  .buyList {

    .td:first-of-type {
      color: @upColor;
    }
    .totalWidth {
      background-color: #253a31;
    }

    @darkUp: #3C753F;
    .tr.hasMyQuantity {
      color: @darkUp;
      line-height: 14px;
      border: 1px dashed @darkUp;

      .td:first-of-type {
        color: @darkUp;
      }
    }
  }

  .orderBookTip {
    position: relative;
    overflow: hidden;
    color: #b5b8c0;
    height: 30px;
    line-height: 30px;
    font-size: 12px;
    background-color: @tradingHeadBgColor;
    border-top: 4px solid @tradingModuleBgColor;
    border-bottom: 4px solid @tradingModuleBgColor;

    .latest {
      position: absolute;
      left: 10px;
      top: 0;
      cursor: pointer;

      em {
        font-size: 16px;
        font-weight: bold;
      }

      em.up {
        color: @upColor;
      }
      em.down {
        color: @downColor;
      }
    }
    .change {
      position: absolute;
      right: 10px;
      top: 0;

      em {
        font-size: 16px;
        font-weight: bold;
      }
    }
  }

  .orderBookListWrap {
    position: relative;
    overflow: hidden;
    width: 354px - @tradingScrollWidth;
  }
}

@media (max-width: @tradingPageMinWidth) { // 1366
  .tradingPage {
    @width: @orderBookWidth - 80px;

    .orderBook {
      width: @width; // 295px
    }
    .orderBookListHead {
      width: @width;
    }
    .orderBookListWrap {
      width: @width - 10px;
    }
    .orderBookTip {
      .mix-hl(23px);

      .latest em, .change em {
        font-size: 12px;
      }
      .latest {
        left: 4px;
      }
      .change {
        right: 4px;
      }
    }
  }
}
@media (max-height: @tradingPageMinHeight) {
  .tradingPage {

    .orderBook {

      .head {
        .mix-hl(23px);

        .orderBookDeep {
          .mix-hl(23px);
        }
      }
    }
    .orderBookListHead {

      .th {
        height: 20px;
        line-height: 22px;
      }
    }
  }
}
</style>
